import { parseTime } from "./ruoyi";
import { ElMessage } from "element-plus";

/**
 * 表格时间格式化
 */
export function formatDate(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === "string") {
      time = time
        .replace(new RegExp(/-/gm), "/")
        .replace("T", " ")
        .replace(new RegExp(/\.[\d]{3}/gm), "");
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

/**
 * 下载文件
 * @param {*} data
 * @param {*} fileName
 * @returns
 */
export function download(data, fileName) {
  if (!data) {
    return;
  }
  let url = window.URL.createObjectURL(new Blob([data]));
  let link = document.createElement("a");
  link.style.display = "none";
  link.href = url;
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

/*
 * cs 2019-12-26
 * 格式化时间
 * @param date 需要格式化的事件
 * @param format 格式化规则yyyy-MM-dd
 * @return 返回时间格式化后的字符串
 */
export function HCFormatDate(date, format) {
  if (!format) {
    return "";
  }
  if (date) {
    if (date.length == 6) {
      date = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + "01";
    }
    if (date.length == 8) {
      date =
        date.substring(0, 4) +
        "-" +
        date.substring(4, 6) +
        "-" +
        date.substring(6, 8);
    }

    if (typeof date != "number") {
      date = date + "";
      if (date.indexOf("T") < 0) {
        date = date.replace(/-/g, "/");
      }
    }
    date = new Date(new Date(date).getTime());
  } else {
    date = new Date();
  }

  let map = {
    M: date.getMonth() + 1,
    d: date.getDate(),
    h: parseInt(date.getHours()),
    m: date.getMinutes(),
    s: date.getSeconds(),
    q: Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds(), //毫秒
  };
  format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
    let v = map[t];
    if (v !== undefined) {
      if (all.length > 1) {
        v = "0" + v;
        v = v.substr(v.length - 2);
      }
      return v;
    } else if (t === "y") {
      return (date.getFullYear() + "").substr(4 - all.length);
    }
    return all;
  });
  return format;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return "";
  return cleanArray(
    Object.keys(json).map((key) => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement("div");
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property];
    if (typeof sourceProperty === "object") {
      target[property] = objectMerge(target[property], sourceProperty);
    } else {
      target[property] = sourceProperty;
    }
  });
  return target;
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += "" + className;
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, laterArgs, context, timestamp, result;

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, laterArgs);
        if (!timeout) context = laterArgs = null;
      }
    }
  };

  return function (...args) {
    laterArgs = args;
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr));
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

export function makeMap(str, expectsLowerCase) {
  const map = Object.create(null);
  const list = str.split(",");
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true;
  }
  return expectsLowerCase ? (val) => map[val.toLowerCase()] : (val) => map[val];
}

export const exportDefault = "export default ";

export const beautifierConf = {
  html: {
    indent_size: "2",
    indent_char: " ",
    max_preserve_newlines: "-1",
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: "separate",
    brace_style: "end-expand",
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: "110",
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true,
  },
  js: {
    indent_size: "2",
    indent_char: " ",
    max_preserve_newlines: "-1",
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: "normal",
    brace_style: "end-expand",
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: "110",
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true,
  },
};

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}

// 下划转驼峰
export function camelCase(str) {
  return str.replace(/_[a-z]/g, (str1) => str1.substr(-1).toUpperCase());
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str);
}

export function isIE() {
  const bw = window.navigator.userAgent;
  const compare = (s) => bw.indexOf(s) >= 0;
  const ie11 = (() => "ActiveXObject" in window)();
  return compare("MSIE") || ie11;
}

/**
 * cs 2022-3-4
 * 通过值 获取键名
 */
export function getObjKey(num, obj, key, code = "value") {
  let tampObj = obj.find((item) => {
    return item[code] == num;
  });
  if (tampObj) {
    return tampObj[key] || num;
  } else {
    return num;
  }
}

export function getArrKey(num, obj, key, code = "value") {
  let tampArr = [];
  obj.map((item, index) => {
    num.map((tmp) => {
      if (item[code] == tmp) {
        tampArr.push(item[key]);
      }
    });
  });
  if (tampArr.length > 0) {
    return tampArr.join(",");
  } else {
    return "";
  }
}

/**
 * 表单验证
 *
 * @param {Object} formData - 表单数据
 *  @param {Array} formData.fieldsList - 源数据
 *  @param {Object} formData.formParam -表单数据
 *
 * @param {Object} subFormData - 子表单数据
 *  @param {Array} subFormData.subListData - 子表单数据
 *  @param {Array} subFormData.subList - 子表单源数据
 *
 * @param {Array} P_AttachmentList - 附件组件列表
 * @param {Array} P_NotionViewList - 阅读意见组件列表
 */
export function checkForm(
  formData,
  subFormData,
  P_AttachmentList,
  P_NotionViewList
) {
  P_AttachmentList = P_AttachmentList || [];
  let isRule = true;
  let ruleError = "";

  //判断附件是否有必填
  for (
    let attachmentIndex = 0;
    attachmentIndex < P_AttachmentList.length;
    attachmentIndex++
  ) {
    let tampAttachment = P_AttachmentList[attachmentIndex];
    //附件为必填项，且附件不存在 或附件列表为空
    if (
      tampAttachment.isRequire &&
      (!tampAttachment.fileList || tampAttachment.fileList.length == 0)
    ) {
      isRule = false;
      break; //跳出循环
    }
  }
  if (isRule == false) {
    ElMessage.error("请上传附件");
    return isRule;
  }

  isRule = true;
  ruleError = "";
  //校验是否必填阅文意见
  if (P_NotionViewList && P_NotionViewList.length) {
    isRule = !P_NotionViewList.some((notionCmp) => {
      //阅文意见必填 提示信息
      ruleError = notionCmp.requireMessage;
      //阅文意见必填 且阅文意见不存在 或 阅文意见列表为空
      return (
        notionCmp.isRequire &&
        (!notionCmp.notionData || !notionCmp.notionData.length)
      );
    });
  }
  if (!isRule) {
    ElMessage.error(ruleError);
    return isRule;
  }

  var requireplaceholder = null;
  var ruleStr = "";
  var ruleArr = [];
  let fieldLen = formData.fieldsList ? formData.fieldsList.length : 0;
  for (let i = 0; i < fieldLen; i++) {
    let item = formData.fieldsList[i];
    if (item.formProp && item.formProp.require && item.formProp.isHaveHtml) {
      console.log(formData.formParam[item.fieldName], item.fieldName);
      if (
        !formData.formParam[item.fieldName] &&
        formData.formParam[item.fieldName] !== 0
      ) {
        isRule = false;
        requireplaceholder = item.formProp.requirePlaceholder || null;
        // ruleStr += item.title + ','
        ruleArr.push(item.title);
      } else if (formData.formParam[item.fieldName] instanceof Array) {
        isRule = formData.formParam[item.fieldName].length != 0;
      }
    }

    // if (!isRule)
    // {
    //     ElMessage.error(requireplaceholder || item.title + "请填写完整");
    // }
    if (item.formProp && item.formProp.regExp) {
      const regExp = new RegExp(item.formProp.regExp);
      let isReg = regExp.test(formData.formParam[item.fieldName]);
      if (!isReg) {
        if (item.formProp.isIntercept) {
          isRule = false;
          ruleError = item.formProp.regError;
        } else {
          alert(item.formProp.regError);
        }
      }
    }

    // if (!isRule)
    // {
    //     break;
    // }
  }
  if (ruleArr.length > 0) {
    ruleStr = ruleArr.join("、");
    ruleError = ruleStr + "请填写完整";
  }
  if (!isRule) {
    ElMessage.error(ruleError);
  }
  if (isRule == false) {
    throw new Error("必填项验证不通过");
  }
  //子表单验证
  if (
    subFormData &&
    subFormData.subListData &&
    subFormData.subListData.constructor == Array
  ) {
    for (let kk = 0; kk < subFormData.subListData.length; kk++) {
      let subListData = subFormData.subListData[kk].subListData;
      let subListName = subFormData.subListData[kk].subListName;
      let findTampObj = subFormData.subList.find((subItem) => {
        return subItem.subListName == subListName;
      });
      //如果在表头数据中找不到 或者没有fields 属性对象 直接跳转循环
      if (!findTampObj || !findTampObj.fields) {
        break;
      }
      for (let j = 0; j < subListData.length; j++) {
        // let field = subListData[j].field;
        //遍历 表头中的属性
        for (var k = 0; k < findTampObj.fields.length; k++) {
          let fieldItem = findTampObj.fields[k];
          if (
            fieldItem.formProp &&
            fieldItem.formProp.require &&
            !subListData[j][fieldItem.fieldName]
          ) {
            ElMessage.error(fieldItem.title + "不能为空!");
            isRule = false;
            break;
          }
        }
        //验证不通过跳出循环
        if (!isRule) {
          break;
        }
      }
      //验证不通过跳出循环
      if (!isRule) {
        break;
      }
    }
  }
  return isRule;
}

/**
 * 前端判断角色
 * @param {} roleName
 * @returns
 */
export function hasRoleWithRoleName(roleName, userRoleKey) {
  var hasRole = false;
  let roles = roleName.split(",");
  roles.map((roleItem) => {
    userRoleKey.map((item) => {
      if (item.roleName == roleItem) {
        hasRole = true;
      }
    });
  });
  return hasRole;
}

/**
 * 数组去重
 * @param {} P_Arr  ["1","2"]
 */
export function arrDistinct(P_Arr) {
  let tampObj = {};
  P_Arr.forEach((pre_item) => {
    if (pre_item) {
      tampObj[pre_item] = pre_item;
    }
  });
  let tampArr = [];
  Object.keys(tampObj).forEach((pre_key) => {
    tampArr.push(pre_key);
  });
  return tampArr;
}

/**
 * 根据value从树中获取label
 */
export function getLabelFromTree(
  P_Value,
  P_Tree,
  P_LabelKey = "label",
  P_ValueKey = "value"
) {
  //递归将树展开
  let treeList = [];
  if (P_Tree) {
    getChidrenList(P_Tree, treeList);
  }
  let findObj = treeList.find((pre_item) => {
    return pre_item[P_ValueKey] == P_Value;
  });
  if (findObj) {
    return findObj[P_LabelKey];
  } else {
    return P_Value;
  }
}

function getChidrenList(P_ChildrenList, P_List) {
  P_ChildrenList.forEach((pre_item) => {
    P_List.push(pre_item);
    if (pre_item.children && pre_item.children.length > 0) {
      getChidrenList(pre_item.children, P_List);
    }
  });
}

const regex = new RegExp(`^\\s+function`);
// json解析（支持函数解析）
export function reviver(key, value) {
  if (typeof value === "string") {
    // 检查是否为对象字符串
    if (value.startsWith("{") && value.endsWith("}")) {
      try {
        // 尝试将对象字符串解析为对象
        return JSON.parse(value, reviver);
      } catch (e) {
        // 解析失败则返回原始字符串
        return value;
      }
    }
    // 检查是否为函数字符串
    else if (value.startsWith("function") || regex.test(value)) {
      // 将函数字符串解析为函数
      return new Function("return " + value)();
    }
  }
  return value;
}

// 判断是否为图片类型文件
export function isImgFile(fileName) {
  var suffix = `(bmp|jpg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|jpeg|BMP|JPG|PNG|TIF|GIF|PCX|TGA|EXIF|FPX|SVG|PSD|CDR|PCD|DXF|UFO|EPS|AI|RAW|WMF|WEBP|JPEG)`;
  var regular = new RegExp(`.*\.${suffix}`);
  return regular.test(fileName);
}

// 判断是否为视屏
export function isVideoFile(fileName) {
  var suffix = `(swf|flv|mp4|rmvb|avi|mpeg|ra|ram|mov|wmv)`;
  var regular = new RegExp(`.*\.${suffix}`);
  return regular.test(fileName);
}

//判断是否为音频
export function isAudioFile(fileName) {
  var suffix = `(mp3|wav|wma|ogg|ape|acc)`;
  var regular = new RegExp(`.*\.${suffix}`);
  return regular.test(fileName);
}

// 判断是否为文本
export function isTextFile(fileName) {
  var suffix = `(txt|json|java|sql|js|css|html|yaml|md|py)`;
  var regular = new RegExp(`.*\.${suffix}`);
  return regular.test(fileName);
}

//获取第一个显示的菜单路由
export function getFirstShowRouter(P_RouterList) {
  let valueToReturn = null;
  for (let i = 0; P_RouterList.length; i++) {
    let pre_router = P_RouterList[i];
    if (pre_router.meta.show) {
      valueToReturn = pre_router;
      break;
    }
  }
  if (!valueToReturn) {
    valueToReturn = P_RouterList[0];
  }
  return valueToReturn;
}

/**
 * 可复用的异常处理
 * @param {Function} fun
 */
export function handleError(fun) {
  return async function (...args) {
    try {
      await fun.call(this, ...args);
    } catch (error) {}
  };
}

//获取pdf预览参数
export function buildPDFPreviewUrl(P_Options) {
  let params = {
    file: "", //文件链接
    download: false, //是否下载
    filename: "", //文件名称
    qyfile: window.HC_config.VUE_APP_QUAN_YUE || false, //是否圈阅
    print: false, //显示打印
    presentationMode: false,
  };
  if (window.HC_config.VUE_APP_VIEWER_BODY_BG_COLOR) {
    //预览界面背景颜色
    params.bodyBgColor = window.HC_config.VUE_APP_VIEWER_BODY_BG_COLOR;
  }
  params = Object.assign(params, P_Options);
  const urlParamsStr = buildUrlParams(params);
  return `/hc-pdf/web/viewer.html?${urlParamsStr}`;
}

//构建参数
export function buildUrlParams(params) {
  return Object.keys(params)
    .map(
      (key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
    )
    .join("&");
}
